/**
 * module:  繁殖记录
 * avator:   渣
 * table:  nc_growth_log,nc_livestock,nc_pasture,nc_house
 */
var express = require('express');
var router = express.Router();
var zSend = require('./controller');

const db = require('../../../db/db');

router.get('/list',( req, res, next )=>{
    const {currentPage = 1, pageSize = 5, F_Title = '', F_Org_Id = '', F_HouseId = ''} = req.query;
    
    // 构建WHERE条件（防止SQL注入）
    let whereClause = '';
    const queryValues = [];
    
    if(F_Title) {
        whereClause += ' AND g.F_Title = ?';
        queryValues.push(F_Title);
    }
    if(F_Org_Id) {
        whereClause += ' AND l.F_Org_Id = ?';
        queryValues.push(F_Org_Id);
    }
    if(F_HouseId) {
        whereClause += ' AND l.F_HouseId = ?';
        queryValues.push(F_HouseId);
    }
    
    // 计算总记录数的SQL
    const countSql = `
        SELECT COUNT(*) as total from nc_livestock as l
        left join nc_growth_log as g on l.F_Id = g.F_liveid
        left join nc_pasture as p on l.F_Org_Id = p.F_Id
        left join nc_house as h on l.F_HouseId = h.F_Id
        WHERE 1=1 ${whereClause};
    `;
    
    // 先查询总记录数
    db.query(countSql, queryValues, (countErr, countResult) => {
        if(countErr) {
            console.error('统计总记录数失败:', countErr);
            return res.send(zSend('服务器内部错误', 500));
        }
        
        const total = countResult[0].total;
        const totalPages = Math.max(1, Math.ceil(total / pageSize)); // 计算总页数
        const effectivePage = Math.min(parseInt(currentPage), totalPages); // 实际有效页码
        
        // 分页查询SQL（使用预处理语句）
        const dataSql = `
            SELECT g.F_Id,l.F_Title,l.F_IMEI,g.F_Title as growthTitle, g.F_EsTimateTime, g.F_SjTimateTime,g.F_Opert,g.F_Phone,g.F_Address, p.F_Title as pastureName, h.F_Title as houseName,g.F_Remark,g.F_CreateTime
            from nc_livestock as l
            left join nc_growth_log as g on l.F_Id = g.F_liveid
            left join nc_pasture as p on l.F_Org_Id = p.F_Id
            left join nc_house as h on l.F_HouseId = h.F_Id
            WHERE 1=1 ${whereClause}
            ORDER BY g.F_CreateTime DESC
            LIMIT ?, ?;
        `;
        
        // 再查询当前页数据（使用有效页码计算偏移量）
        const paginationValues = [...queryValues, (effectivePage - 1) * pageSize, parseInt(pageSize)];
        db.query(dataSql, paginationValues, (dataErr, data) => {
            if(dataErr) {
                console.error('查询数据失败:', dataErr);
                return res.send(zSend('服务器内部错误', 500));
            }
            
            res.send(zSend({
                list: data || [], // 确保返回空数组而非null
                total: total
            }));
        });
    });
});
// 添加繁殖记录
router.post('/add',( req, res, next )=>{
    const {F_liveid,F_Title,F_EsTimateTime,F_SjTimateTime,F_Opert,F_Phone,F_Address,F_Remark} = req.body;
    if(!F_liveid || !F_EsTimateTime||!F_Title){
        res.send(zSend('参数错误', 400))
    }
    const F_Id = Date.now();
    const F_CreateTime = new Date().toLocaleString();
    const sql = `INSERT INTO nc_growth_log (F_Id,F_liveid,F_Title,F_EsTimateTime,F_SjTimateTime,F_Opert,F_Phone,F_Address,F_Remark,F_CreateTime) VALUES (?,?,?,?,?,?,?,?,?,?)`;
    db.query(sql, [F_Id,F_liveid,F_Title,F_EsTimateTime,F_SjTimateTime,F_Opert,F_Phone,F_Address,F_Remark,F_CreateTime], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('添加成功'))
        }
    })
})
// 删除繁殖记录
router.post('/delete',( req, res, next )=>{
    const {F_Id} = req.body;
    if(!F_Id){
        res.send(zSend('参数错误', 400))
    }
    const sql = `DELETE FROM nc_growth_log WHERE F_Id = ?`;
    db.query(sql, [F_Id], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('删除成功'))
        }
    })
})
// 修改繁殖记录
router.post('/update',( req, res, next )=>{
    const {F_Id,F_liveid,F_Title,F_EsTimateTime,F_SjTimateTime,F_Opert,F_Phone,F_Address,F_Remark} = req.body;
    if(!F_Id || !F_liveid || !F_EsTimateTime||!F_Title){
        res.send(zSend('参数错误', 400))
    }
    const sql = `UPDATE nc_growth_log SET F_liveid = ?,F_Title = ?,F_EsTimateTime = ?,F_SjTimateTime = ?,F_Opert = ?,F_Phone = ?,F_Address = ?,F_Remark = ? WHERE F_Id = ?`;
    db.query(sql, [F_liveid,F_Title,F_EsTimateTime,F_SjTimateTime,F_Opert,F_Phone,F_Address,F_Remark,F_Id], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('修改成功'))
        }
    })
})


module.exports = router;